package com.lrabbit.rabbit.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lrabbit.rabbit.api.user.request.SysUserPageReq;
import com.lrabbit.rabbit.user.entity.SysUserDO;
import com.lrabbit.rabbit.user.mapper.SysUserDOMapper;
import com.lrabbit.rabbit.user.service.SysUserService;
import com.lrabbit.utils.StrUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 用户表 服务实现类
 *
 * @author common-generator
 * @since 2024-06-22
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDOMapper, SysUserDO> implements SysUserService {

    @Resource
    private SysUserService sysUserService;

    @Override
    public Page listPageSysUserList(SysUserPageReq pageReq) {

        QueryWrapper<SysUserDO> queryWrapper = new QueryWrapper<>();
        // lambda查询
        LambdaQueryWrapper<SysUserDO> lambdaQueryWrapper = queryWrapper.lambda();

        // 【推荐写法】
        // lambdaQueryWrapper.eq(!StrUtils.isBlank(pageReq.getId()), SysUserDO::getId, pageReq.getId());

        // [精确查询-方式1]
        if (!StrUtils.isBlank(pageReq.getId())) {
            lambdaQueryWrapper.eq(SysUserDO::getId, pageReq.getId());
        }

        // [精确查询-方式2]
//      Map<String,Object>mapParam = new HashMap<>();
//      mapParam.put("id", pageReq.getId());
//      lambdaQueryWrapper.allEq(mapParam, false);

        // [模糊查询-方式1] 1.查询参数对象 2.模糊查询字段(实体类字段)，逗号分割 3.查询Wrapper
//      PageReqUtils.allLike(pageReq, "id,name", lambdaQueryWrapper);

        // [时间范围]
        if (!StrUtils.isBlank(pageReq.getLpStartDate())) {
            lambdaQueryWrapper.between(SysUserDO::getCreateTime, pageReq.getCreateTime(), pageReq.getModifyTime());
        }

        // [排序] 根据字段排序
        if (!StrUtils.isBlank(pageReq.getLpSortName())) {
            queryWrapper.select().orderBy(true, "asc".equalsIgnoreCase(pageReq.getLpSortType()), pageReq.getLpSortName());
        } else {
            // 默认按创建时间降序
            lambdaQueryWrapper.orderByDesc(SysUserDO::getCreateTime);
        }

        // 调用分页查询方法
        Page pageList = sysUserService.page(pageReq.initPage(), queryWrapper);
        log.info("分页查询结束-查询条数:{}, 总条数:{}", pageList.getRecords().size(), pageList.getTotal());

        return pageList;
    }
}
